﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using PhoneManager.LanguageText;

namespace PhoneManager
{
    public partial class FrmSyncContacts : FrmDefault
    {
        private int QtdSIM = 0;
        private int QtdPhone = 0;
        private string FindLetter = "";
        private string FindText = "";
        private bool ISFirst = false;
        private List<LiveGooglePhoneBook> SyncContacts = new List<LiveGooglePhoneBook>();


        public FrmSyncContacts()
        {
            InitializeComponent();
        }
        public FilterTypeEnum Filter { get; set; }

        private void BntCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void CalcPages(int IniPage)
        {
            int QtdItens = 0;
            foreach (LiveGooglePhoneBook item in SharedLib.LiveContacts)
            {
                bool ok = true;
                switch (Filter)
                {
                    case FilterTypeEnum.NotSync:
                        ok = (!item.IsSync);
                        break;
                    case FilterTypeEnum.Live:
                        ok = (item.OriginalFrom == BookSyncEnum.Live);
                        break;
                    case FilterTypeEnum.Google:
                        ok = (item.OriginalFrom == BookSyncEnum.Goolgle);
                        break;
                    case FilterTypeEnum.LiveGoogle:
                        ok = true;
                        break;
                }
                if (FindLetter != "")
                {
                    if (!item.OriginalName.ToUpper().Trim().StartsWith(FindLetter))
                    {
                        ok = false;
                    }
                }
                else if (FindText != "")
                {
                    if (item.OriginalName.ToUpper().IndexOf(FindText) < 0)
                    {
                        ok = false;
                    }
                }
                if (ok)
                {
                    QtdItens++;
                }
            }
            foreach (LiveGooglePhoneBook item in SharedLib.GoogleContacts)
            {
                bool ok = true;
                switch (Filter)
                {
                    case FilterTypeEnum.NotSync:
                        ok = (!item.IsSync);
                        break;
                    case FilterTypeEnum.Live:
                        ok = (item.OriginalFrom == BookSyncEnum.Live);
                        break;
                    case FilterTypeEnum.Google:
                        ok = (item.OriginalFrom == BookSyncEnum.Goolgle);
                        break;
                    case FilterTypeEnum.LiveGoogle:
                        ok = true;
                        break;
                }
                if (FindLetter != "")
                {
                    if (!item.OriginalName.ToUpper().Trim().StartsWith(FindLetter))
                    {
                        ok = false;
                    }
                }
                else if (FindText != "")
                {
                    if (item.OriginalName.ToUpper().IndexOf(FindText) < 0)
                    {
                        ok = false;
                    }
                }
                if (ok)
                {
                    QtdItens++;
                }
            }
            int PageMax;
            if (QtdItens < Properties.Settings.Default.DefaultSyncItemsOfPage)
            {
                PageMax = 1;
            }
            else
            {
                PageMax = (int)QtdItens / Properties.Settings.Default.DefaultSyncItemsOfPage;
                if ((PageMax * Properties.Settings.Default.DefaultSyncItemsOfPage) < QtdItens)
                {
                    PageMax++;
                }
            }
            UpDnPag.Maximum = PageMax;
            ISFirst = true;
            UpDnPag.Value = IniPage;
            ISFirst = false;
            UpDnPag.Minimum = 1;
            LblTotPg.Text = ResourcesText.WordOf + " " + PageMax.ToString();
        }
        private void LoadContacts(bool Calc)
        {
            LoadContacts(Calc, 1);
        }

        private void LoadContacts(bool Calc, int Page)
        {

            if (Calc)
            {
                CalcPages(Page);
            }

            this.Cursor = Cursors.WaitCursor;
            flowLayoutPanel.Controls.Clear();
            QtdSIM = 0;
            QtdPhone = 0;

            int StartItem = ((((int)UpDnPag.Value) - 1) * Properties.Settings.Default.DefaultSyncItemsOfPage) + 1;
            int EndItem = StartItem + Properties.Settings.Default.DefaultSyncItemsOfPage - 1;

            int pos = 0;



            foreach (LiveGooglePhoneBook item in SyncContacts)
            {
                bool ok = true;
                switch (Filter)
                {
                    case FilterTypeEnum.NotSync:
                        {
                            this.Text = ResourcesText.TitSync + " " + ResourcesText.TitNotSyncFilter;
                            ok = (!item.IsSync);
                            if (!ok && item.PhoneIndex != "")
                            {
                                PhoneBook pb = SharedLib.FindPhoneByID(item.PhoneIndex, false);
                                if (pb == null)
                                {
                                    ok = true;
                                }
                                else
                                {
                                    if (item.Name != pb.Name || item.Number != pb.Number)
                                    {
                                        ok = true;
                                    }
                                }
                            }
                            if (!ok && item.SIMIndex != "")
                            {
                                PhoneBook pb = SharedLib.FindPhoneByID(item.SIMIndex, true);
                                if (pb == null)
                                {
                                    ok = true;
                                }
                                else
                                {
                                    if (item.Name != pb.Name || item.Number != pb.Number)
                                    {
                                        ok = true;
                                    }
                                }
                            }
                        }
                        break;
                    case FilterTypeEnum.Live:
                        this.Text = ResourcesText.TitSync + " " + ResourcesText.TitOnlyLiveFilter;
                        ok = (item.OriginalFrom == BookSyncEnum.Live);
                        break;
                    case FilterTypeEnum.Google:
                        this.Text = ResourcesText.TitSync + " " + ResourcesText.TitOnlyGoogleFilter;
                        ok = (item.OriginalFrom == BookSyncEnum.Goolgle);
                        break;
                    case FilterTypeEnum.LiveGoogle:
                        this.Text = ResourcesText.TitSync + " " + ResourcesText.TitOnlyLiveGoogleFilter;
                        ok = true;
                        break;
                }
                if (FindLetter != "")
                {
                    if (!item.OriginalName.ToUpper().Trim().StartsWith(FindLetter))
                    {
                        ok = false;
                    }
                }
                else if (FindText != "")
                {
                    if (item.OriginalName.ToUpper().IndexOf(FindText) < 0)
                    {
                        ok = false;
                    }
                }
                if (ok)
                {
                    pos++;
                    if (pos < StartItem)
                    {
                        ok = false;
                    }
                }
                if (ok)
                {
                    if (pos  > EndItem)
                    {
                        break;
                    }
                    UCSyncPhonebook UPB = new UCSyncPhonebook();
                    UPB.Index = pos;
                    UPB.LiveGoogleID = item.OriginalID.Trim();
                    UPB.NameContact = item.Name.Trim();
                    UPB.NumberContact = item.Number.Trim();
                    UPB.PhoneID = item.PhoneIndex;
                    UPB.SIMID = item.SIMIndex;
                    UPB.SendPhone = (item.PhoneIndex != "");
                    UPB.SendSIM = (item.SIMIndex != "");
                    UPB.NameLiveGoogleContact = item.OriginalName.Trim();
                    UPB.NumberLiveGoogleContact = item.OriginalNumber.Trim();
                    UPB.From = item.OriginalFrom;
                    UPB.NumberType = item.OriginalNumberType;
                    UPB.IsSync = item.IsSync;
                    UPB.EventUCSyncPhonebook += new UCSyncPhonebook.UCSyncPhonebookEventHandler(UPB_EventUCSyncPhonebook);
                    flowLayoutPanel.Controls.Add(UPB);
                }
            }
            FindText = "";
            FindLetter = "";
            foreach (PhoneBook item in SharedLib.PhonesBook)
            {
                if (item.SIMIndex != "")
                {
                    QtdSIM++;
                }
                if (item.PhoneIndex != "")
                {
                    QtdPhone++;
                }
            }
            string txt = QtdPhone.ToString() + "/" + SharedLib.PhoneBookMEMRanger.Max.ToString();
            LblQtdPhone.Text = txt;
            txt = QtdSIM.ToString() + "/" + SharedLib.PhoneBookSIMRanger.Max.ToString();
            LblQtdSIM.Text = txt;
            this.Cursor = Cursors.Default;

        }

        private void UPB_EventUCSyncPhonebook(object sender, UCSyncPhonebookEventArgs e)
        {
            if (e.SendPhone > 0 && ((UCSyncPhonebook)sender).PhoneID == "")
            {
                if (QtdPhone + e.SendPhone > SharedLib.PhoneBookMEMRanger.Max)
                {
                    SharedLib.MsgAlert(ResourcesText.MsgErrMaxMemoryPhone);
                    ((UCSyncPhonebook)sender).SendPhone = false;
                }
                else
                {
                    QtdPhone += e.SendPhone;
                }
            }
            else if (e.SendPhone < 0 && ((UCSyncPhonebook)sender).PhoneID == "")
            {
                    QtdPhone += e.SendPhone;
            }

            if (e.SendSIM > 0 && ((UCSyncPhonebook)sender).SIMID == "")
            {
                if (QtdSIM + e.SendSIM > SharedLib.PhoneBookSIMRanger.Max)
                {
                    SharedLib.MsgAlert(ResourcesText.MsgErrMaxMemorySIM);
                    ((UCSyncPhonebook)sender).SendSIM = false;
                }
                else
                {
                    QtdSIM += e.SendSIM;
                }
            }
            else if (e.SendSIM < 0 && ((UCSyncPhonebook)sender).SIMID == "")
            {
                QtdSIM += e.SendSIM;
            }
            string txt = QtdPhone.ToString() + "/" + SharedLib.PhoneBookMEMRanger.Max.ToString();
            LblQtdPhone.Text = txt;
            txt = QtdSIM.ToString() + "/" + SharedLib.PhoneBookSIMRanger.Max.ToString();
            LblQtdSIM.Text = txt;
        }
        private void FrmSyncContacts_Shown(object sender, EventArgs e)
        {
            for (double i = 0; i < 1; i += 0.1)
            {
                this.Opacity = i;
                Application.DoEvents();
                Thread.Sleep(30);
            }
            SyncContacts.AddRange(SharedLib.LiveContacts.ToArray());
            SyncContacts.AddRange(SharedLib.GoogleContacts.ToArray());
            SyncContacts.Sort(new OrderLiveGooglePhoneBook());
            LoadContacts(true);
        }

        private void LnkNotSync_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.Filter = FilterTypeEnum.NotSync;
            LoadContacts(true);
        }

        private void LnkLive_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.Filter = FilterTypeEnum.Live;
            LoadContacts(true);
        }

        private void LnkGoogle_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.Filter = FilterTypeEnum.Google;
            LoadContacts(true);
        }

        private void LnkAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.Filter = FilterTypeEnum.LiveGoogle;
            LoadContacts(true);
        }

        private void Lnk_ALL_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FindLetter = "";
            FindText = "";
            TxtFind.Text = "";
            LoadContacts(true);
        }

        private void PctPesq_Click(object sender, EventArgs e)
        {
            FindText = TxtFind.Text.ToUpper().Trim();
            FindLetter = "";
            LoadContacts(true);
        }

        private void Lnk_FindLetter_Click(object sender, EventArgs e)
        {
            FindLetter = ((LinkLabel)sender).Text;
            FindText = "";
            TxtFind.Text = "";
            LoadContacts(true);
        }

        private void UpDnPag_ValueChanged(object sender, EventArgs e)
        {
            if (!ISFirst)
            {
                LoadContacts(false);
            }
        }

        private void BntSave_Click(object sender, EventArgs e)
        {
            this.Opacity = 0.3;
            this.Cursor = Cursors.WaitCursor;
            SharedLib.StartWaitProcessThread();
            bool ErroGSM = false;
            string ErroName = "";
            string ErroNumber = "";
            bool IsChange = false;
            foreach (UCSyncPhonebook item in flowLayoutPanel.Controls)
            {
                LiveGooglePhoneBook lgb = null;
                if (item.From == BookSyncEnum.Live)
                {
                    lgb = SharedLib.FindPhoneByFromLiveGoogleID(BookSyncEnum.Live, item.NumberType, item.LiveGoogleID);
                }
                else if (item.From == BookSyncEnum.Goolgle)
                {
                    lgb = SharedLib.FindPhoneByFromLiveGoogleID(BookSyncEnum.Goolgle, item.NumberType, item.LiveGoogleID);
                }
                if (item.IsRemove)
                {
                    if (item.From == BookSyncEnum.Live)
                    {
                        SharedLib.LiveContacts.Remove(lgb);
                        IsChange = true;
                    }
                    else if (item.From == BookSyncEnum.Goolgle)
                    {
                        SharedLib.GoogleContacts.Remove(lgb);
                        IsChange = true;
                    }
                }
                else
                {
                    if (item.IsHasChange())
                    {
                        //se houve mudança set sync.
                        lgb.IsSync = true;
                        lgb.Name = item.NameContact;
                        lgb.Number = item.NumberContact;
                        IsChange = true;

                        bool AddP = false;
                        bool AddS = false;
                        bool UpdP = false;
                        bool UpdS = false;
                        if (item.SendSIM)
                        {
                            if (item.SIMID != "")
                            {
                                UpdS = true;
                                AddS = false;
                            }
                            else
                            {
                                UpdS = false;
                                AddS = true;
                            }
                        }
                        if (item.SendPhone)
                        {
                            if (item.PhoneID != "")
                            {
                                UpdP = true;
                                AddP = false;
                            }
                            else
                            {
                                UpdP = false;
                                AddP = true;
                            }
                        }
                        bool okAddP = false;
                        bool okAddS = false;
                        bool okUpdP = false;
                        bool okUpdS = false;
                        int IndexP = -1;
                        int IndexS = -1;
                        if (AddP)
                        {
                            IndexP = SharedLib.ModemGSM.PBookPhoneInsert(item.NameContact, item.NumberContact);
                            if (IndexP > 0)
                            {
                                okAddP = true;
                            }
                            else
                            {
                                ErroGSM = true;
                                ErroName = item.NameContact;
                                ErroNumber = item.NumberContact;
                                break;
                            }
                        }
                        if (AddS)
                        {
                            IndexS = SharedLib.ModemGSM.PBookSimInsert(item.NameContact, item.NumberContact);
                            if (IndexS > 0)
                            {
                                okAddS = true;
                            }
                            else
                            {
                                ErroGSM = true;
                                ErroName = item.NameContact;
                                ErroNumber = item.NumberContact;
                                break;
                            }
                        }
                        if (UpdP)
                        {
                            okUpdP = SharedLib.ModemGSM.PBookPhoneUpdate(item.PhoneID, item.NameContact, item.NumberContact);
                            if (!okUpdP)
                            {
                                ErroGSM = true;
                                ErroName = item.NameContact;
                                ErroNumber = item.NumberContact;
                                break;
                            }
                        }
                        if (UpdS)
                        {
                            okUpdS = SharedLib.ModemGSM.PBookSimUpdate(item.SIMID, item.NameContact, item.NumberContact);
                            if (!okUpdS)
                            {
                                ErroGSM = true;
                                ErroName = item.NameContact;
                                ErroNumber = item.NumberContact;
                                break;
                            }
                        }
                        if (okAddP && okAddS)
                        {
                            lgb.PhoneIndex = IndexP.ToString();
                            lgb.SIMIndex = IndexS.ToString();
                            PhoneBook pb = new PhoneBook();
                            pb.Name = item.NameContact;
                            pb.Number = item.NumberContact;
                            pb.PhoneIndex = IndexP.ToString();
                            pb.SIMIndex = IndexS.ToString();
                            SharedLib.PhonesBook.Add(pb);
                        }
                        else if (okAddP && okUpdS)
                        {
                            lgb.PhoneIndex = IndexP.ToString();
                            PhoneBook pb = SharedLib.FindPhoneByID(item.SIMID, true);
                            PhoneBook npb = new PhoneBook();
                            npb.Name = item.NameContact;
                            npb.Number = item.NumberContact;
                            npb.PhoneIndex = IndexP.ToString();
                            npb.SIMIndex = pb.SIMIndex;
                            SharedLib.PhonesBook.Remove(pb);
                            SharedLib.PhonesBook.Add(npb);
                        }
                        else if (okAddP && !okUpdS && !okAddS)
                        {
                            lgb.PhoneIndex = IndexP.ToString();
                            PhoneBook npb = new PhoneBook();
                            npb.Name = item.NameContact;
                            npb.Number = item.NumberContact;
                            npb.PhoneIndex = IndexP.ToString();
                            npb.SIMIndex = "";
                            SharedLib.PhonesBook.Add(npb);
                        }
                        else if (okAddS && okUpdP)
                        {
                            lgb.SIMIndex = IndexS.ToString();
                            PhoneBook pb = SharedLib.FindPhoneByID(item.PhoneID, false);
                            PhoneBook npb = new PhoneBook();
                            npb.Name = item.NameContact;
                            npb.Number = item.NumberContact;
                            npb.PhoneIndex = pb.PhoneIndex;
                            npb.SIMIndex = IndexS.ToString();
                            SharedLib.PhonesBook.Remove(pb);
                            SharedLib.PhonesBook.Add(npb);
                        }
                        else if (okAddS && !okUpdP && !okAddP)
                        {
                            lgb.SIMIndex = IndexS.ToString();
                            PhoneBook npb = new PhoneBook();
                            npb.Name = item.NameContact;
                            npb.Number = item.NumberContact;
                            npb.PhoneIndex = "";
                            npb.SIMIndex = IndexS.ToString();
                            SharedLib.PhonesBook.Add(npb);
                        }
                        if ((okUpdS || okUpdP) && !okAddP && !okAddS)
                        {
                            PhoneBook pb = SharedLib.FindPhoneByID(item.PhoneID, false);
                            if (pb == null)
                            {
                                pb = SharedLib.FindPhoneByID(item.SIMID, true);
                            }
                            PhoneBook npb = new PhoneBook();
                            npb.Name = item.NameContact;
                            npb.Number = item.NumberContact;
                            npb.PhoneIndex = pb.PhoneIndex;
                            npb.SIMIndex = pb.SIMIndex;
                            SharedLib.PhonesBook.Remove(pb);
                            SharedLib.PhonesBook.Add(npb);
                        }
                    }
                }
            }
            SharedLib.EndWaitProcessThread();
            this.Cursor = Cursors.Default;
            if (ErroGSM)
            {
                string Msg = ResourcesText.ErrSaveAction + "\n";
                Msg += ResourcesText.WordName +  " : " + ErroName + "\n";
                Msg += ResourcesText.WordNumber +  " : " + ErroNumber + "\n";
                SharedLib.MsgAlert(Msg);
            }
            else if (IsChange)
            {
                SharedLib.MsgAlert(ResourcesText.SyncOKAct);
            }
            else
            {
                SharedLib.MsgAlert(ResourcesText.NoChangeAct);
            }
            if (SharedLib.LiveUser.Trim() != "")
            {
                SharedLib.SaveLiveBookFileName(PhoneStorageEnum.Live, SharedLib.CreateNameBook(SharedLib.ModemGSM.IMEI + SharedLib.LiveUser));
            }
            if (SharedLib.GoogleUser.Trim() != "")
            {
                SharedLib.SaveLiveBookFileName(PhoneStorageEnum.Goolgle, SharedLib.CreateNameBook(SharedLib.ModemGSM.IMEI + SharedLib.GoogleUser));
            }
            SyncContacts.Clear();
            SyncContacts.AddRange(SharedLib.LiveContacts.ToArray());
            SyncContacts.AddRange(SharedLib.GoogleContacts.ToArray());
            SyncContacts.Sort(new OrderLiveGooglePhoneBook());
            flowLayoutPanel.Controls.Clear();
            LoadContacts(true, (int)UpDnPag.Value);
            this.Opacity = 1;
        }

        private void LnkUp_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            foreach (UCSyncPhonebook item in flowLayoutPanel.Controls)
            {
                item.ChangeNameContact(item.NameContact.ToUpper());
            }
        }

        private void LnkUFL_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            foreach (UCSyncPhonebook item in flowLayoutPanel.Controls)
            {
                string[] param = item.NameContact.Split(' ');
                string name = "";
                foreach (string p in param)
                {
                    if (p.Length > 2)
                    {
                        name += p.Substring(0, 1).ToUpper() + p.Substring(1).ToLower() + " ";
                    }
                    else
                    {
                        if (p.ToLower() == item.NameContact.ToLower())
                        {
                            name += p.ToUpper();
                        }
                        else
                        {
                            name += p.ToLower() + " ";
                        }
                    }
                }
                item.ChangeNameContact(name.Trim());
            }
        }

        private void LnkLW_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            foreach (UCSyncPhonebook item in flowLayoutPanel.Controls)
            {
                item.ChangeNameContact(item.NameContact.ToLower());
            }
        }
    }
    public enum FilterTypeEnum
    {
        NotSync = 0,
        Live = 1,
        Google = 2,
        LiveGoogle = 3
    }

}
